// pages/detail-search/index.js
import {getSearchHot,getSearchSuggest,getSearchResult} from "../../service/api_search"
import debounce from "../../utils/debounce"
import strToNode from "../../utils/strToNode"
import {playerStore} from "../../store/index"

let debounceSearchChange = debounce(getSearchSuggest,300)

Page({
  data: {
    hotKeywords:[],
    suggestSongs:[],
    searchValue:"",
    resultSongs:[],
    suggestSongsNode:[]
  },
  onLoad: function (options) {
    this.getPageData()
  },
  // 初始化页面数据
  getPageData(){
    getSearchHot().then(res=>{
      this.setData({hotKeywords:res.result.hots})
    })
  },
  //获取建议搜索数据
  searchChange(event){
    let searchValue =  event.detail
    this.setData({searchValue})
    if(!searchValue.length){
      this.setData({suggestSongs:[],resultSongs:[]})
      debounceSearchChange.cancel()
      return
    }
    debounceSearchChange(searchValue).then(res=>{ 
      // 获取建议关键词
      let suggestSongs = res.result.allMatch
      this.setData({suggestSongs})
    
      // 转成node节点
      let suggestKeywords = suggestSongs.map(item=>item.keyword)
      let suggestSongsNode = []
      for (const keyword of suggestKeywords) {
        let node = strToNode(keyword,searchValue)
        suggestSongsNode.push(node)
      }
      this.setData({suggestSongsNode})
    })
  },
  // 回车开始搜索时
  searchAction(){
    let searchValue = this.data.searchValue
    getSearchResult(searchValue).then(res=>{
      this.setData({resultSongs:res.result.songs})
    })
  },
  // 点击关键词搜索
  keywordClick(event){
    const keyword = event.currentTarget.dataset.keyword
    this.setData({searchValue:keyword})
    this.searchAction()
  },
  // 添加到歌曲列表
  songBtn(event){
    let index = event.currentTarget.dataset.index
    playerStore.setState("playList",this.data.resultSongs)
    playerStore.setState("playListIndex",index)
  }
})